#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <errno.h>
#include <string.h>

#define COMMAND_VALUESIZE       100

#define LOG_TAG "wlan_test"
#define WLAN_PROC_ERR -45

#define WIFI_SCAN_COMMAND "nmcli dev wifi"
#define WIFI_CONNECT_COMMAND "nmcli dev wifi connect"
// #define WIFI_PING_COMMAND "ping -c 3 192.168.1.1"     // -I wlan0
// #define WIFI_PING_COMMAND "ping -I p2p0 -c 3 192.168.1.1"
#define WIFI_PING_COMMAND "ping -I wlan0 -c 3 www.baidu.com"

#define SSID "AI300"
#define PASSWORD "hanweiai"


void *wlan_test(void *argv)
{
    char scan_result[1024*10];
    // 扫描周围的WIFI热点
    printf("Scanning for available WIFI networks...\n");
    FILE* scan_output = popen(WIFI_SCAN_COMMAND, "r");
    if (scan_output == NULL) {
        printf("Error scanning for WIFI networks.\n");
        // err_code = WLAN_PROC_ERR;
        return (void *)-1;
    }
    sleep(5);
    while (fgets(scan_result, sizeof(scan_result), scan_output) != NULL) {
        printf("%s", scan_result);
    }
    pclose(scan_output);

    // 连接指定的WIFI网络
    char ssid[64] = SSID;
    char password[64] = PASSWORD;
    printf("Connecting to WIFI network %s...\n", ssid);
    char connect_command[256];
    // snprintf(connect_command, sizeof(connect_command), "%s %s password %s", WIFI_CONNECT_COMMAND, ssid, password);
    snprintf(connect_command, sizeof(connect_command), "%s %s password %s ifname wlan0", WIFI_CONNECT_COMMAND, ssid, password);
    int connect_status = system(connect_command);
    sleep(2);
    if (connect_status != 0) {
        printf("Failed to connect to WIFI network.\n");
        // err_code = WLAN_PROC_ERR;
        return (void *)-1;
    }

    // 检查是否能够ping通外网
    printf("Testing internet connectivity...\n");
    sleep(3);
    int ping_status = system(WIFI_PING_COMMAND);
    if (ping_status != 0) {
        // err_code = WLAN_PROC_ERR;
        // char result[COMMAND_VALUESIZE] = RESULT_FAIL;
        printf("Failed to ping external server. WIFI test failed.\n");
        return (void *)-1;
    }

    printf("WIFI test successful. Connected to WIFI network and able to access the internet.\n");
    return 0;
}


int main(int argc, char *argv[]) {

    // system("ifconfig wlan0 down");

    int err_code = 0;
    char buf[COMMAND_VALUESIZE] = "wlan_test";

    printf("wifi wlan0 test start...\n");

    int ret;
    while(1)
    {
        ret = (int)wlan_test(argv[0]);
        if (ret) {
            err_code = -1;
            break;
        }else{
            err_code = 0;
            break;
        }
    }
   
    if (err_code)
    {
        printf("wifi 测试失败\n");
        system("echo \"$(date)：WiFi测试失败\" >> /userfs/all.txt");
    }
    else
    {
        printf("wifi 测试成功\n");
        system("echo \"$(date)：WiFi测试成功\" >> /userfs/all.txt");
    }


    // system("ifconfig wlan0 down");
        
    return 0;
}